package test.ground.netty.netty.my;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.timeout.IdleStateHandler;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 客户端
 */
public class Client {

    public ClientReconnectHandler.ChannelContainer start(String host, int port){
        EventLoopGroup group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();

        bootstrap.group(group);                                 //设置线程组
        bootstrap.channel(NioSocketChannel.class);              //设置管道
        final ClientReconnectHandler clientReconnectHandler = new ClientReconnectHandler(bootstrap, host, port) {
            @Override
            public ChannelHandler[] channelHandlers() {
                return new ChannelHandler[]{
                        this,//重连的handler
//                new LoggingHandler(LogLevel.INFO),                //日志handler
                        new MessageDecoder(),
                        new MessageEncoder(),
                        //4s没发消息就发一个心跳过去
                        new IdleStateHandler(0, 4, 0, TimeUnit.SECONDS), //心跳检查handler
                        new ClientHeartBeatHandler(),
                        new ChannelInboundHandlerAdapter() {
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                System.out.println("回来"+msg);
                            }
                        }
                };
            }
        };

        System.err.println("client is ready......");
        synchronized (bootstrap) {
            bootstrap.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel socketChannel) throws Exception {
                    socketChannel.pipeline().addLast(clientReconnectHandler.channelHandlers());//正常情况时的连接绑定
                }
            });
            try {
                bootstrap.connect(host,port).sync();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return clientReconnectHandler.getChannel();
    }
    public static void main(String[] args) {
        ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
        ClientReconnectHandler.ChannelContainer container = new Client().start("127.0.0.1", 8888);
        AtomicInteger i = new AtomicInteger();
        executorService.scheduleAtFixedRate(()->{
            if (container.isActive()) {
                System.out.println("我还在");
                container.getChannel().writeAndFlush(new Message("你好啊"+i.incrementAndGet()));
            }

        },800,800,TimeUnit.MILLISECONDS);
    }
}